<template>
  <el-dialog v-model="dialogVisible" title="企业信息列表" width="75%" align-center :close-on-click-modal="false" @close="handleClose">
    <div class="app-container">
      <div class="settle-manage">
        <el-form :inline="true" :model="dataFilter" class="search-form">
          <el-form-item label="所属商户" class="form-item-wrapper">
            <el-select v-model="dataFilter.tenantId" placeholder="请选择所属商户" clearable style="width: 150px;"
              @change="loadLocationData" filterable remote :remote-method="searchMerchant">
              <el-option v-for="item in merchantList" :key="item.id" :label="item.tenantName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="所在地点位置" class="form-item-wrapper">
            <el-tree-select v-model="dataFilter.locationIds" :data="fullLocationTree" multiple collapse-tags collapse-tags-tooltip 
              :render-after-expand="false" show-checkbox :filter-node-method="filterNodeMethod" filterable node-key="id"
              value-key="id" :props="locationTreeProps" placeholder="请选择所在地点位置" clearable style="width: 180px" />
          </el-form-item>

          <el-form-item label="结算周期" class="form-item-wrapper">
            <el-select v-model="dataFilter.billingCycle" placeholder="请选择结算周期" clearable style="width: 130px">
              <el-option v-for="item in billingCycleOption" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="计费配置" class="form-item-wrapper">
            <el-select v-model="dataFilter.isConfig" placeholder="请选择计费配置" clearable style="width: 100px">
              <el-option v-for="item in billingSettingOption" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="企业简称" class="form-item-wrapper">
            <el-input v-model="dataFilter.shortName" placeholder="请输入企业简称" style="width: 150px" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="sourceData.list" border highlight-current-row stripe row-key="id" style="width: 100%" v-loading="loading">
          <el-table-column label="企业简称" prop="shortName" />
          <el-table-column label="联系人" prop="contactPerson" />
          <el-table-column label="联系电话" prop="customerPhone" />
          <el-table-column label="所在地点位置" prop="location" min-width="100" />
          <el-table-column label="经营场景" prop="businessScenario" />
          <el-table-column label="所属商户" prop="tenantName" />
          <el-table-column label="计费配置" prop="isConfig" width="85">
            <template #default="{ row }">
              <span>{{ row.isConfig == 1 ? '已配置' : '未配置' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="triggerSetting(row)">
                开始配置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
      </div>
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { 
  getEnterprise, 
  getMerchantByName,
  getLocationTree
} from "@/api/settle";
import Pagination from "@/components/Pagination/Index.vue";
import { LocationTreeNode } from '@/api/types/location'

const emit = defineEmits(['setting'])

// 弹窗显示状态
const dialogVisible = ref(false)
const loading = ref(false)

const dataFilter = reactive({
  shortName: undefined as string | undefined,
  tenantId: undefined as number | undefined,
  billingCycle: undefined as number | undefined,
  locationIds: [],
  isConfig: undefined as number | undefined,
  isSettle: 0,
});

const billingCycleOption = ref<any>([
  { name: '按月结算', value: 0 },
  { name: '按季度结算', value: 1 },
  { name: '按半年结算', value: 2 },
  { name: '按年结算', value: 3 },
])

const billingSettingOption = ref<any>([
  { name: '未配置', value: 0 },
  { name: '已配置', value: 1 },
])

// 商户列表
const merchantList = ref<any[]>([]);

// 获取商户列表
const getMerchantList = (name?: string) => {
  // 使用新的按名称查询接口
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
};

const searchMerchant = (name: string) => {
  getMerchantList(name)
}

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const sourceData = reactive({
  list: [] as any[],
});

const getList = () => {
  loading.value = true;
  getEnterprise({
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }).then((res: any) => {
    loading.value = false;
    console.log("res", res);
    sourceData.list = res.data.records || [];
    pageProps.value.total = res.data.total || 0;
  })
  .catch((err: any) => {
    loading.value = false;
    console.error("err", err);
    sourceData.list = [];
    pageProps.value.total = 0;
  });
};

const handleSearch = () => {
  pageProps.value.pageNum = 1; // 搜索时重置到第一页
  getList();
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

const onReset = () => {
  dataFilter.shortName = undefined;
  dataFilter.tenantId = undefined;
  dataFilter.billingCycle = undefined;
  dataFilter.locationIds = [];
  dataFilter.isConfig = undefined;
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  getList(); // 重置后重新获取数据
};

const triggerSetting = (row: any) => {
  dialogVisible.value = false
  emit('setting', row.shortName)
}

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
const locationTreeProps = ref({
  label: 'name'
});

// 加载地点位置数据
const loadLocationData = async () => {
  try {
    if (!dataFilter.tenantId) {
      fullLocationTree.value = []
      return
    }
    
    const res = await getLocationTree(dataFilter.tenantId)
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  }
}

const filterNodeMethod = (value: string, data: any) => {
  return value ? data.name.includes(value) : true;
}

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true
  onReset()
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
.app-container {
  flex: 1;
  box-shadow: 1px 2px 4px 1px rgba(0, 0, 0, 0);
  padding: 0;
}
.form-item-wrapper {
  margin-right: 10px;
}
</style>